<template>
  <div class="pagination">
    <button @click="changePageNum(pageNo-1)" :disabled="pageNo===1">上一页</button>
    <button v-show="startAndEnd.start>1" @click="changePageNum(1)">1</button>
    <span v-show="startAndEnd.start >2">...</span>
    <button :class="{active:pageNo===startAndEnd.start + index}" v-for="(_,index) in (startAndEnd.end-startAndEnd.start + 1)" :key="_" @click="changePageNum(startAndEnd.start + index)">{{startAndEnd.start + index}}</button>
    <button v-show="startAndEnd.end < totalPage -1">···</button>
    <button v-show="startAndEnd.end < totalPage" @click="changePageNum(totalPage)">{{totalPage}}</button>
    <button @click="changePageNum(pageNo+1)" :disabled="pageNo===totalPage">下一页</button>

    <span>共 {{total}} 条</span>
  </div>
</template>

<script>
export default {
  name: 'Pagination',
  data() {
    return {};
  },
  props: ['total', 'pageNo', 'pageSize', 'continues'],
  computed: {
    // 1. 计算总页码
    totalPage() {
      const { total, pageSize } = this;
      console.log(total, pageSize);
      return Math.ceil(total / pageSize);
    },
    // 2. 计算开始和结束页码
    startAndEnd() {
      const { continues, pageSize, pageNo, totalPage } = this;
      let start, end;
      if (continues > totalPage) {
        start = 1; // 现在的起始页
        end = totalPage; // 结束就是最大页码
      } else {
        start = pageNo - parseInt(continues / 2);
        end = pageNo + parseInt(continues / 2);

        // 起始页小于1的情况

        if (start < 1) {
          start = 1; // 起始页不能小于1 极端只能从1开始 也就是最小是1
          end = continues;
        }

        // 当结束页码超出了总页码的情况
        if (end > totalPage) {
          end = totalPage; //
          start = totalPage - continues + 1; //
        }
      }
      return { start, end };
    }
  },
  methods: {
    changePageNum(pageNum) {
      this.$emit('get-pageNo', pageNum);
    }
  }
};
</script>

<style lang="less" scoped>
.pagination {
  text-align: center;
  button {
    margin: 0 5px;
    background-color: #f4f4f5;
    color: #606266;
    outline: none;
    border-radius: 2px;
    padding: 0 4px;
    vertical-align: top;
    display: inline-block;
    font-size: 13px;
    min-width: 35.5px;
    height: 28px;
    line-height: 28px;
    cursor: pointer;
    box-sizing: border-box;
    text-align: center;
    border: 0;

    &[disabled] {
      color: #c0c4cc;
      cursor: not-allowed;
    }

    &.active {
      cursor: not-allowed;
      background-color: #c81623;
      color: #fff;
    }
  }
  span {
    display: inline-block;
    line-height: 28px;
    font-size: 14px;
    color: gray;
    vertical-align: middle;
  }
}
</style>